<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item label="对账日期：" prop="timeDate">
                        <el-date-picker v-model="queryParams.timeDate" type="daterange" range-separator="至"
                            start-placeholder="开始时间" end-placeholder="结束时间" @change="handleTimeChange"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="客户：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责人：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="回款状态：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="模糊查询" prop="workName">
                        <el-input style="width: 120px;" v-model="queryParams.workName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="20" justify="space-between">
                    <el-col :span="1.5">
                        <el-row :gutter="20">
                            <!-- <el-col :span="1.5">
                                <el-button @click="hanleOpenAdd" plain type="success" icon="CirclePlus">
                                    收款</el-button>
                            </el-col> -->
                            <el-col :span="1.5">
                                <el-button @click="hanleOpenBadDebt()" icon="DocumentRemove" plain type="primary">
                                    坏账历史记录</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button plain @click="exportPurchaseList" type="success"
                                    icon="DocumentDelete">下载EXCEL</el-button>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="1.5">
                        <div>
                            <strong class="mr20">总订单金额：{{ totalAmountObj.totalOrderAmount || 0 }}</strong>
                            <strong class="mr20">总差价金额：{{ totalAmountObj.totalPriceDifference || 0 }}</strong>
                            <strong class="mr20">总对账金额：{{ totalAmountObj.totalReconciliationAmount || 0 }}</strong>
                            <strong class="mr20">总收款金额：{{ totalAmountObj.totalReceivableAmount || 0 }}</strong>
                            <strong class="mr20">总坏账金预：{{ totalAmountObj.totalBadDebtAmount || 0 }}</strong>
                            <strong>总欠款金额：{{ totalAmountObj.totalArrearsAmount || 0 }}</strong>
                        </div>
                    </el-col>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="dataList">
                <el-table-column label="所属公司" prop="companyName" align="center"></el-table-column>
                <el-table-column label="对账日期" prop="reconciliationDate" align="center"></el-table-column>
                <el-table-column label="付款方名称" prop="payer" align="center"></el-table-column>
                <el-table-column label="客户类别" prop="customerType" align="center"></el-table-column>
                <el-table-column label="项款来源" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.source == 0">微定制订单</span>
                        <span v-if="scope.row.source == 1">销售单</span>
                    </template>
                </el-table-column>
                <el-table-column label="订单总金额" prop="totalOrderAmount" align="center"></el-table-column>
                <el-table-column label="对账金额" prop="reconciliationAmount" align="center"></el-table-column>
                <el-table-column label="差价" prop="priceDifference" align="center"></el-table-column>
                <el-table-column label="收款金额" prop="collectedAmount" align="center"></el-table-column>
                <el-table-column label="坏账金额" prop="badDebt" align="center"></el-table-column>
                <el-table-column label="欠款金额" prop="pendingCollect" align="center"></el-table-column>
                <el-table-column label="付款截止时间" prop="endDate" align="center"></el-table-column>
                <el-table-column label="回款状态" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.collectStatus == 0" style="color: #F75F51;">未回款</span>
                        <span v-else-if="scope.row.collectStatus == 1" style="color: #E6A33F;">部分回款</span>
                        <span v-else-if="scope.row.collectStatus == 2" style="color: #68C23D;">已回款</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作人" prop="operationName" align="center"></el-table-column>
                <el-table-column label="备注" prop="remark" align="center"></el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="200px">
                    <template #default="scope">
                        <el-tooltip content="收款">
                            <el-button @click="handlOpenPayment(scope.row)" link type="warning">
                                <i style="font-size: 18px;" class="iconfont icon-daifukuan"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="坏账">
                            <el-button @click="handlOpenOneClickBalance(scope.row)" link type="primary">
                                <i style="font-size: 18px;" class="iconfont icon-pingbibeifen"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除">
                            <el-button @click="handleDelete(scope.row)" :style="{ fontSize: '18px' }" link type="danger"
                                icon="Close"></el-button>
                        </el-tooltip>
                        <el-tooltip content="订单详情">
                            <el-button @click="handlOpenReconciliationDetails(scope.row)" :style="{ fontSize: '18px' }"
                                link type="primary" icon="DocumentCopy"></el-button>
                        </el-tooltip>
                        <el-tooltip content="收款详情">
                            <el-button @click="handlOpenReceivableDetails(scope.row)" link type="warning">
                                <i style="font-size: 18px;" class="iconfont icon-qiandaizi-copy"></i>
                            </el-button>
                        </el-tooltip>

                    </template>
                </el-table-column>

            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 新增收款 -->
        <AddCollectionOfPayments :visible="addCollectionOfPaymentsVisible"
            @close="addCollectionOfPaymentsVisible = false" />
        <!-- 收款 -->
        <Payment :visible="paymentVisible" :initList="paymentRow" :allPaymentCardList="allPaymentCardList"
            @close="handlOpenPaymentClose" @submit="getList" />
        <!-- 坏账 -->
        <BadDebts :visible="oneClickBalanceVisible" :initList="oneClickBalanceObj" @submit="getList"
            @close="oneClickBalanceVisible = false" />
        <!-- 收款详情 -->
        <PaymentDetails :visible="paymentDetailsVisible" :initList="paymentDetailsRow" :paymentDetails="paymentDetails"
            @close="paymentDetailsVisible = false" />
        <!-- 订单详情 -->
        <ReconciliationDetails :visible="reconciliationDetailsVisible" @close="handleReconciliationDetailsClose" />
        <!-- 历史记录 -->
        <HistoryRecords :visible="historyRecordsVisible" :initList="historyRecordsList"
            @close="historyRecordsVisible = false" />
    </div>
</template>
<script setup lang="ts">
import { type FormInstance } from 'element-plus';

import { getAccountsReceivableListApi, deleteAccountsReceivableApi } from '@/api/sj/financialManagement/accountsReceivable/index';
import { getAllPaymentCardApi } from '@/api/sj/financialManagement/paymentCard/index'
import { getFormattedTimestamp } from '@/utils/dateFormat';

import Payment from './components/payment.vue'
import usePayment from '@/hooks/financialManagement/accountsPayable/usePayment'
import ReconciliationDetails from './components/reconciliationDetails.vue';
import useReconciliationDetails from '@/hooks/financialManagement/accountsPayable/useReconciliationDetails'
import PaymentDetails from './components/paymentDetails.vue';
import HistoryRecords from './components/historyRecords.vue';
import useHistoryRecords from '@/hooks/financialManagement/accountsPayable/useHistoryRecords'
import BadDebts from './components/badDebts.vue';
import useOneClickBalance from '@/hooks/financialManagement/accountsPayable/useOneClickBalance'


/** 新增收款 */
import AddCollectionOfPayments from './components/addCollectionOfPayments.vue'
import useAddCollectionOfPayments from '@/hooks/financialManagement/accountsReceivable/useAddCollectionOfPayments'
const { addCollectionOfPaymentsVisible, } = useAddCollectionOfPayments();
/** 付款 */
const { paymentVisible, paymentRow, handlOpenPayment, handlOpenPaymentClose } = usePayment();
/** 订单详情 */
const { reconciliationDetailsVisible, paymentDetailsVisible, paymentDetailsRow,
    paymentDetails, handlOpenReceivableDetails, handlOpenReconciliationDetails, handleReconciliationDetailsClose } = useReconciliationDetails();
/** 收款详情 */
/** 坏账 */
const { oneClickBalanceVisible, oneClickBalanceObj, handlOpenOneClickBalance } = useOneClickBalance();
/** 历史记录 */
const { historyRecordsVisible, historyRecordsList, hanleOpenBadDebt, } = useHistoryRecords();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const queryFormRef = ref<FormInstance>();

const data = reactive<pageDataOnlyQuery<any>>({
    queryParams: {
        timeDate: '',
        startDate: '',
        endDate: '',
        pageSize: 10,
        pageNum: 1
    }
});

const { queryParams } = toRefs(data);

const loading = ref(false);
const dataList = ref<any>([]);
const totalData = ref(0);
const voucherVisible = ref(false);
const totalAmountObj = ref({
    totalOrderAmount: 0,
    totalPriceDifference: 0,
    totalReconciliationAmount: 0,
    totalReceivableAmount: 0,
    totalBadDebtAmount: 0,
    totalArrearsAmount: 0
});
const allPaymentCardList = ref<any>([]);

const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.startDate = '';
    queryParams.value.endDate = '';
    queryParams.value.timeDate = '';
    handleQuery();
};

/** 日期选择 */
const handleTimeChange = (val: any) => {
    queryParams.value.startDate = val[0];
    queryParams.value.endDate = val[1];
};

/** 列表删除 */
const handleDelete = (row: any) => {
    ElMessageBox.confirm('删除后，此订单将转化为未对账状态，请问您确定么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            try {
                const { code } = await deleteAccountsReceivableApi(row.id);
                if (code === 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功!'
                    });
                    getList();
                }
            } catch (error) {

            }

        })
        .catch(() => { });
};

const getList = async () => {
    loading.value = true;
    try {
        const { data } = await getAccountsReceivableListApi(queryParams.value);

        totalAmountObj.value = data;
        dataList.value = data.dataPage.records;
        totalData.value = data.dataPage.total;
        loading.value = false;
    } catch (error) {
        loading.value = false;
    }
};

const exportPurchaseList = () => {
    proxy?.download('/system/accountsReceivable/export', { ...queryParams.value }, `应收款${getFormattedTimestamp()}.xlsx`);
};

/** 获取所有收款卡 */
const getAllPaymentCard = async () => {
    const { data } = await getAllPaymentCardApi();
    allPaymentCardList.value = data;
};

onMounted(() => {
    getList();
    getAllPaymentCard();
});

</script>
<style lang="scss" scoped></style>